import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart' hide WidgetPaddingX;
import 'package:hotpot/basic/app_colors.dart';
import 'package:hotpot/extensions/data.dart';
import 'package:hotpot/http/http_api.dart';
import 'package:hotpot/models/create_order_req.dart';
import 'package:hotpot/models/floor.dart';
import 'package:hotpot/models/res_partner.dart';
import 'package:hotpot/models/shop_detail.dart';
import 'package:hotpot/pages/order/widgets/confirma_pin_widget.dart';
import 'package:hotpot/pages/order/widgets/product_detail_widget.dart';
import 'package:hotpot/pages/order/widgets/scan_widget.dart';
import 'package:hotpot/pages/order/widgets/shopcar_widget.dart';
import 'package:hotpot/pages/order/widgets/success_widget.dart';
import 'package:hotpot/pages/table/table_page.dart';
import 'package:hotpot/route/route_ext.dart';
import 'package:hotpot/route/route_mixin.dart';
import 'package:hotpot/route/routes.dart';
import 'package:hotpot/utils/product_utils.dart';
import 'package:hotpot/utils/user_utils.dart';
import 'package:hotpot/widgets/styles/num_point.dart';
import 'package:hotpot/widgets/widget_ext.dart';
import 'package:hotpot/widgets/z_container.dart';
import 'package:hotpot/widgets/z_image.dart';
import 'package:uuid/uuid.dart';

class OrderPage extends StatefulWidget {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> with ArgMixin {
  var cateIndex = 0.obs;
  var twoCateId = 0.obs;

  var shopCarCount = 0.obs;
  var showShopCar = false.obs;
  var showPin = false.obs;
  var showSuccess = false.obs;

  late int initStaffId;

  double get totalPrice =>
      orderData.lines?.where((e) => e.comboParentId == null).map((e) => e.priceSubtotal ?? 0).fold<double>(0, (p, e) => p + e) ??
      0;

  var showScan = false.obs;
  var partner = ResPartner().obs;

  var showDetail = false.obs;
  ShopDetailProductProducts? currProduct;

  late CreateOrderReq orderData;

  late FloorTables table;

  late bool required;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.baColor,
      body: Stack(
        children: [
          Column(
            children: [
              _header(),
              7.hSizedBox,
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: (detail.posCategorys?.where((e) => e.parentId == null && (required == (e.required ?? false))) ?? [])
                      .map(cateBox)
                      .toList(),
                ),
              ),
              Obx(
                () {
                  var cate = detail.posCategorys![cateIndex.value];
                  var cateList = <ShopDetailPosCategorys>[];
                  if (cate.childId?.isNotEmpty ?? false) {
                    cateList.addAll(detail.posCategorys!.where((e) => e.parentId.firstValue == cate.id.toString()));
                    twoCateId.value = cateList.first.id!;
                  } else {
                    twoCateId.value = 0;
                  }
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (cateList.isNotEmpty)
                        SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: Row(
                            children: [
                              ...cateList.map(cateItem),
                            ],
                          ),
                        ).alignLeft(),
                      // 'Choose Dishes'.text(size: 9, color: Colors.white, bold: true).paddingOnly(left: 7).alignLeft(),
                      15.hSizedBox,
                      Obx(
                        () {
                          var productList = <ShopDetailProductProducts>[];
                          if (twoCateId.value == 0) {
                            var temp = detail.productProducts!.where((e) => e.posCategIds!.contains(cate.id));
                            productList.addAll(temp);
                          } else {
                            var temp = detail.productProducts!.where((e) => e.posCategIds!.contains(twoCateId.value));
                            productList.addAll(temp);
                          }
                          return GridView.builder(
                            padding: const EdgeInsets.symmetric(horizontal: 14).r,
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 5,
                              childAspectRatio: 100 / 118,
                              crossAxisSpacing: 8.r,
                              mainAxisSpacing: 16.r,
                            ),
                            itemBuilder: (_, index) => _item(index, productList),
                            itemCount: productList.length,
                          ).expanded();
                        },
                      ),
                    ],
                  );
                },
              ).expanded(),
            ],
          ).positioned(top: 0, bottom: 0, right: 0, left: 0),
          _detail(),
          _shopCar(),
          Obx(() {
            return ConfirmaPinWidget(() => showPin.value = false, (staffId) {
              var partnerId = int.tryParse(partner.value.partnerId?.first ?? '');
              orderData.partnerId = partnerId;
              orderData.mobileSend = true;
              HttpApi.createOrder(
                detail.posSession!.id!,
                table.id!,
                staffId,
                detail.posSession!.loginNumber!,
                orderData.toJson(),
              ).then((value) {
                HttpApi.sendOrderToPreparation(orderData.id!).then((value) {
                  if (required) {
                    Routes.order
                        .popAndPushNamed(arg: {'data': orderData, 'table': table, 'required': false, 'initStaffId': staffId});
                    // Routes.requiredBanner.popAndPushNamed(arg: {'data': orderData, 'table': table});
                  } else {
                    showSuccess.value = true;
                  }
                  showPin.value = false;
                });
              });
            }).visibility(showPin.value);
          }).positioned(right: 0, top: 0, bottom: 0, left: 0),
          Obx(() {
            return const SuccessWidget().visibility(showSuccess.value);
          }).positioned(right: 0, top: 0, bottom: 0, left: 0),
          Obx(() {
            return ScanWidget(() => showScan.value = false, (data) {
              partner.value = data;
            }).visibility(showScan.value);
          }).positioned(right: 0, top: 0, bottom: 0, left: 0),
        ],
      ),
    ).popScope(onPopInvoked: (pop) {
      if (pop) return;
      checkOrderSave();
    });
  }

  Widget cateBox(ShopDetailPosCategorys cate) {
    return Obx(() {
      var index = detail.posCategorys!.indexOf(cate);
      return Stack(
        children: [
          if (index == cateIndex.value)
            const Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ZContainer(
                  color: Color(0xFFFFDE22),
                  height: 1,
                  width: 40,
                  showShadows: true,
                  shadowColor: Color(0xFFFFDE22),
                  blurRadius: 3,
                  spreadRadius: 1,
                  shadowOffset: Offset(0, 0),
                ),
              ],
            ).positioned(bottom: 5, left: 0, right: 0),
          ZContainer(
            height: 17,
            padding: const EdgeInsets.symmetric(horizontal: 10),
            alignment: Alignment.center,
            radius: 8,
            // color: index == cateIndex.value ? const Color(0xFF1C1C1C) : Colors.transparent,
            child: cate.name.text(color: index == cateIndex.value ? Colors.black : const Color(0xFF8A8A8A), bold: true, size: 8),
          ).gestureDetector(onTap: () => setState(() => cateIndex.value = index)),
        ],
      );
    });
  }

  @override
  void loadArg(Map<String, dynamic> arg) {
    // TODO: implement loadArg
    orderData = arg['data'];
    table = arg['table'];
    required = arg['required'];
    initStaffId = arg['initStaffId'];
    int index;
    if (required) {
      index = detail.posCategorys!.indexWhere((e) => e.required == true);
    } else {
      index = detail.posCategorys!.indexWhere((e) => e.required != true);
    }
    selectCate(index);
  }

  void selectCate(int index) {
    cateIndex.value = index;
    // productList.clear();
    // var cate = detail.posCategorys![index];
    // var ids = [cate.id, ...cate.childId ?? []];
    // var temp = detail.productProducts!.where((e) => e.posCategIds!.isNotEmpty && e.posCategIds!.every((e) => ids.contains(e)));
    // productList.addAll(temp);
  }

  Widget? _item(int index, List<ShopDetailProductProducts> productList) {
    var data = productList[index];
    var count = ProductUtils.count(orderData.lines ??= [], data).obs;
    return Stack(
      children: [
        ZContainer(
          width: double.infinity,
          margin: const EdgeInsets.only(top: 0, bottom: 0),
          color: const Color(0xFFFFFFFF),
          radius: 6,
          side: const BorderSide(width: 2, color: Color(0xFFF4F4F2)),
          child: Column(
            children: [
              4.hSizedBox,
              ZImage.memory(bytes: data.image.bytes, width: 54, height: 54, fit: BoxFit.fill),
              4.hSizedBox,
              // data.cnName.text(size: 7, color: Colors.white, bold: true, textAlign: TextAlign.center),
              data.name.text(maxLines: 2, size: 7, color: Colors.black, textAlign: TextAlign.center).sizedBox(height: 18),
              7.hSizedBox,
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: [
                    ...data.allergySource?.map((e) =>
                            ZImage.memory(bytes: e.bytes, width: 10, height: 10, fit: BoxFit.cover).paddingOnly(right: 5)) ??
                        [],
                  ],
                ),
              ).sizedBox(height: 10),
              4.hSizedBox,
              (data.lstPrice.fixed == '0.00' ? '' : data.lstPrice.fixed).text(size: 9, bold: true, color: Colors.black),
            ],
          ),
        ),
        Obx(
          () => NumPoint(
            count.value,
            color: const Color(0xFF22CE67),
            textColor: Colors.white,
            textSize: 7,
            minSize: 11,
          ),
        ).positioned(right: 3, top: 3),
        // Obx(
        //   () => const IconBox(Icons.close, 11, 9, bgColor: Colors.red).gestureDetector(onTap: () {
        //     if (data.comboIds?.isNotEmpty ?? false) {
        //       print('comboIds');
        //     } else if (data.attributeLineIds?.isNotEmpty ?? false) {
        //       ProductUtils.deleteProduct(orderData.lines ??= [], products: data);
        //       count.value = ProductUtils.count(orderData.lines ??= [], data);
        //       shopCarCount.value = orderData.lines!.map((e) => e.qty ?? 0).fold(0, (p, e) => p + e);
        //     } else {
        //       ProductUtils.deleteProduct(orderData.lines ??= [], products: data);
        //       count.value = ProductUtils.count(orderData.lines ??= [], data);
        //       shopCarCount.value = orderData.lines!.map((e) => e.qty ?? 0).fold(0, (p, e) => p + e);
        //     }
        //   }).visibility(count.value > 0),
        // ).positioned(top: 13, right: 0),
        if (data.productTag?.isNotEmpty ?? false)
          Transform.rotate(
            angle: -45 * pi / 180,
            child: ZContainer(
              color: const Color(0xFF0022AA),
              // margin: const EdgeInsets.only(top: 9),
              padding: const EdgeInsets.symmetric(horizontal: 5),
              height: 8,
              radius: 4,
              alignment: Alignment.center,
              child: data.productTag.text(bold: true, color: Colors.white, size: 5),
            ),
          ).positioned(top: 20),
      ],
    ).gestureDetector(onTap: () {
      if (data.comboIds?.isNotEmpty ?? false) {
        print('comboIds');
        // } else if (data.attributeLineIds?.isNotEmpty ?? false) {
        //   currProduct = data;
        //   showDetail.value = true;
      } else {
        currProduct = data;
        showDetail.value = true;
        // showDetail.value = false;
        // ProductUtils.addProductLine(orderData.lines ??= [], data);
        // count.value = ProductUtils.count(orderData.lines ??= [], data);
        // shopCarCount.value = orderData.lines!.map((e) => e.qty ?? 0).fold(0, (p, e) => p + e);
      }
    });
  }

  Widget cateItem(ShopDetailPosCategorys cate) {
    return Obx(() {
      var select = twoCateId.value == cate.id;
      return Stack(
        children: [
          Column(
            children: [
              cate.name.text(size: 7, color: select ? Colors.white : const Color(0xFFC9B9B9), bold: true),
            ],
          ).paddingOnly(left: 7, bottom: 5, right: 14).gestureDetector(onTap: () => twoCateId.value = cate.id!),
          2.line(color: select ? const Color(0xFF22CE67) : Colors.transparent).positioned(left: 7, right: 14, bottom: 0),
        ],
      );
    });
  }

  void checkOrderSave() {
    showDialog(
      context: context,
      builder: (_) => Scaffold(
        backgroundColor: Colors.black12,
        body: ZContainer(
          color: const Color(0xFF1F1D2B),
          radius: 5,
          width: 150,
          height: 80,
          child: Column(
            children: [
              5.hSizedBox,
              '提示'.text(size: 10, bold: true, color: Colors.white),
              '是否保存订单'.text(size: 8, textAlign: TextAlign.center, color: Colors.white).paddingOnly(top: 15).expanded(),
              Row(
                children: [
                  '仅退出'
                      .text(size: 8, textAlign: TextAlign.center, color: Colors.white)
                      .gestureDetector(onTap: () => Get.close(2))
                      .expanded(),
                  '保存并退出'.text(size: 8, textAlign: TextAlign.center, color: Colors.white).gestureDetector(onTap: () {
                    var partnerId = int.tryParse(partner.value.partnerId?.first ?? '');
                    orderData.partnerId = partnerId;
                    orderData.mobileSend = false;
                    HttpApi.createOrder(
                      detail.posSession!.id!,
                      table.id!,
                      initStaffId,
                      detail.posSession!.loginNumber!,
                      orderData.toJson(),
                    ).then((_) => Get.close(2));
                  }).expanded(),
                ],
              ),
              5.hSizedBox,
            ],
          ),
        ).alignCenter(),
      ),
    );
  }

  _header() {
    return ZContainer(
      height: 33,
      child: Row(
        children: [
          Row(
            children: [
              'images/img_back.png'.assetImage(width: 7, height: 11).paddingOnly(left: 11, right: 13).gestureDetector(
                  onTap: () => Routes.requiredBanner
                      .popAndPushNamed(arg: {'data': orderData, 'table': table, 'required': required, 'staffId': initStaffId})),
              UserUtils.companyName.text(color: Colors.black, size: 10, bold: true),
            ],
          ).sizedBox(width: 150),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              'T${table.name}'.text(size: 12, bold: true, color: table.color.color),
              '#${orderData.trackingNumber}'.text(size: 6, bold: true, color: Colors.black),
            ],
          ).expanded(),
          // const IconBox(Icons.highlight_remove_rounded, 18, 16, bgColor: Colors.transparent)
          //     .gestureDetector(
          //     onTap: () => Routes.requiredBanner.popAndPushNamed(
          //         arg: {'data': orderData, 'table': table, 'required': required, 'staffId': initStaffId}))
          //     .alignRight()
          //     .sizedBox(width: 150),

          ZContainer(
            alignment: Alignment.centerRight,
            width: 150,
            child: ZContainer(
              color: const Color(0xFF22CE67),
              radius: 18,
              alignment: Alignment.center,
              width: 82,
              height: 23,
              margin: const EdgeInsets.only(right: 12, top: 5),
              child: Builder(
                builder: (_) {
                  var lines =
                      orderData.lines?.where((e) => e.comboParentId == null && e.hasSend == 0).map((e) => e.productId).toSet() ??
                          {};
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 8.wSizedBox,
                      // Column(
                      //   mainAxisAlignment: MainAxisAlignment.center,
                      //   children: [
                      //     const IconBox(Icons.shopping_cart, 16, 14, bgColor: Colors.transparent),
                      //
                      //   ],
                      // ),
                      Row(
                        children: [
                          '${lines.length}/'.text(size: 9, bold: true, color: Colors.white),
                          '${(orderData.customerCount ?? 0) * 5}'.text(size: 9, bold: true, color: const Color(0xFF39FF88)),
                        ],
                      ),
                      4.wSizedBox,
                      Container(height: 11.w, width: 1.w, color: const Color(0xFFFFFFFF)),
                      5.wSizedBox,
                      // Column(
                      //   crossAxisAlignment: CrossAxisAlignment.start,
                      //   children: [
                      //     'Total'.text(size: 10, bold: true, color: const Color(0xFF7F7F7F)),
                      //   ],
                      // ),
                      // 8.wSizedBox,
                      totalPrice.fixed.text(size: 12, bold: true, color: Colors.white),
                    ],
                  );
                },
              ),
            ).gestureDetector(onTap: () => showShopCar.value = true),
          ),
        ],
      ),
    );
  }

  _detail() {
    return Obx(() {
      var line = CreateOrderReqLines();
      line
        ..qty = 1
        ..hasSend = 0
        ..priceUnit = currProduct?.lstPrice
        ..uuid = const Uuid().v1()
        ..priceSubtotal = currProduct?.lstPrice ?? 0
        ..productId = currProduct?.id
        ..fullProductName = currProduct?.name
        ..attributeMultiValue = {}
        ..attributeValueIds = [];
      return ProductDetailWidget(currProduct, line, () {
        var lines =
            orderData.lines?.where((e) => e.comboParentId == null && e.hasSend == 0).map((e) => e.productId).toSet() ?? {};
        lines.add(line.productId);
        if (lines.length > (orderData.customerCount ?? 0) * 5) {
          showToast('已超过最大值');
          return;
        }
        if (currProduct?.attributeLineIds?.isNotEmpty ?? false) {
          ProductUtils.addProductAttr(orderData.lines ??= [], line);
        } else if (currProduct != null) {
          ProductUtils.addProductLine(orderData.lines ??= [], currProduct!, line.qty ?? 1);
        }
        showDetail.value = false;
        shopCarCount.value = orderData.lines!.map((e) => e.qty ?? 0).fold(0, (p, e) => p + e);
        setState(() {});
      }, () => showDetail.value = false).visibility(showDetail.value);
    }).positioned(right: 0, top: 0, bottom: 0, left: 0);
  }

  _shopCar() {
    return Obx(() {
      return ShopcarWidget(
        table.name ?? '',
        table.color,
        orderData,
        (count) {
          showShopCar.value = false;
        },
        () {
          // showPin.value = true;
          showShopCar.value = false;
          var partnerId = int.tryParse(partner.value.partnerId?.first ?? '');
          orderData.partnerId = partnerId;
          orderData.mobileSend = true;
          HttpApi.createOrder(
            detail.posSession!.id!,
            table.id!,
            initStaffId,
            detail.posSession!.loginNumber!,
            orderData.toJson(),
          ).then((value) {
            HttpApi.sendOrderToPreparation(orderData.id!).then((value) {
              if (required) {
                Routes.order
                    .popAndPushNamed(arg: {'data': orderData, 'table': table, 'required': false, 'initStaffId': initStaffId});
                // Routes.requiredBanner.popAndPushNamed(arg: {'data': orderData, 'table': table});
              } else {
                showSuccess.value = true;
              }
              showPin.value = false;
            });
          });
        },
      ).visibility(showShopCar.value);
    }).positioned(right: 0, top: 0, bottom: 0, left: 0);
  }
}
